package com.lenovo.manufacture;

import android.os.Bundle;
import android.util.SparseArray;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.GridView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;

import com.google.gson.Gson;
import com.lenovo.manufacture.model.UserPlStep;
import com.lenovo.manufacture.model.UserPlStepInfo;
import com.lenovo.manufacture.model.UserProductionLine;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

public class Race4Activity extends AppCompatActivity {

    private GridView id_four_gv;
    private ArrayAdapter<UserPlStepInfo.DataBean> adapter;
    private UserProductionLine userProductionLine;
    private List<UserPlStep.DataBean> upsList = new ArrayList<>();
    private SparseArray<UserPlStepInfo.DataBean> dataBeanSparseArray = new SparseArray(20);
    private int responseCount = 0;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_four);
        initView();
        getUserProductionLine();
    }

    private void getUserProductionLine() {
        OkHttpClient client = new OkHttpClient().newBuilder()
                .build();
        MediaType mediaType = MediaType.parse("text/plain");
        RequestBody body = RequestBody.create(mediaType, "");
        Request request = new Request.Builder()
                .url("http://192.168.1.103:8085/dataInterface/UserProductionLine/search?position=3")
                .method("POST", body)
                .build();
        client.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                runOnUiThread(() -> Toast.makeText(Race4Activity.this, "失败" + e.getLocalizedMessage(), Toast.LENGTH_SHORT).show());
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                if (response.isSuccessful()) {
                    userProductionLine = new Gson().fromJson(response.body().string(), UserProductionLine.class);
                    if (userProductionLine != null || userProductionLine.getData().get(0) != null) {
                        getAllUserPlStep(userProductionLine.getData().get(0).getProductionLineId());
                    }
                } else {
                    runOnUiThread(() -> Toast.makeText(Race4Activity.this, "失败" + response.code(), Toast.LENGTH_SHORT).show());
                }
            }
        });
    }

    private void getAllUserPlStep(int productionLineId) {
        OkHttpClient client = new OkHttpClient().newBuilder()
                .build();
        MediaType mediaType = MediaType.parse("text/plain");
        RequestBody body = RequestBody.create(mediaType, "");
        Request request = new Request.Builder()
                .url("http://192.168.1.103:8085/dataInterface/UserPlStep/search?userProductionLineId=" + productionLineId)
                .method("POST", body)
                .build();
        client.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                runOnUiThread(() -> Toast.makeText(Race4Activity.this, "失败" + e.getLocalizedMessage(), Toast.LENGTH_SHORT).show());
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                if (response.isSuccessful()) {
                    UserPlStep userPlStep = new Gson().fromJson(response.body().string(), UserPlStep.class);

                    List<UserPlStep.DataBean> data = userPlStep.getData();
                    if (data.isEmpty()) {
                        runOnUiThread(() -> Toast.makeText(Race4Activity.this, "UserPlStep isEmpty", Toast.LENGTH_SHORT).show());
                    } else {
                        upsList.clear();
                        upsList.addAll(data);
                        getUserPlStepInfo();
                    }


                } else {
                    runOnUiThread(() -> Toast.makeText(Race4Activity.this, "失败" + response.code(), Toast.LENGTH_SHORT).show());
                }
            }
        });
    }

    private void initView() {
        id_four_gv = (GridView) findViewById(R.id.four_gv);
        adapter = new ArrayAdapter<UserPlStepInfo.DataBean>(this, R.layout.item_gv_four) {
            @Override
            public int getCount() {
                return 20;
            }

            @NonNull
            @Override
            public View getView(int position, @Nullable View convertView, @NonNull ViewGroup parent) {
                convertView = LayoutInflater.from(getContext()).inflate(R.layout.item_gv_four, parent, false);
                ViewHolder viewHolder = new ViewHolder(convertView);
                UserPlStepInfo.DataBean dataBean = dataBeanSparseArray.get(19-position);
                if (dataBean != null) {
                    viewHolder.tv_rname.setText(dataBean.getPlStepName());
                    int power = dataBean.getPower();
                    viewHolder.tv_item_four_gv_numleft.setText("" + power);

                    UserProductionLine.DataBean tpl = userProductionLine.getData().get(0);
                    if (tpl.getStageId() == position) {
                        viewHolder.line_item_gv_four.setBackgroundResource(R.drawable.item_four_gv);
                    }

                }

                return convertView;
            }
        };
        id_four_gv.setAdapter(adapter);

    }

    public void getUserPlStepInfo() {
        responseCount = 0;
        OkHttpClient client = new OkHttpClient().newBuilder()
                .build();
        MediaType mediaType = MediaType.parse("application/x-www-form-urlencoded");
        for (int i = 0; i < upsList.size(); i++) {
            final int index = i;
            RequestBody body = RequestBody.create(mediaType, "id=" + upsList.get(i).getId());
            Request request = new Request.Builder()
                    .url("http://192.168.1.103:8085/dataInterface/UserPlStepInfo/getInfo")
                    .method("POST", body)
                    .addHeader("Content-Type", "application/x-www-form-urlencoded")
                    .build();
            client.newCall(request).enqueue(new Callback() {
                @Override
                public void onFailure(Call call, IOException e) {
                    refresh();
                }

                @Override
                public void onResponse(Call call, Response response) throws IOException {
                    if (response.isSuccessful()) {
                        UserPlStepInfo userPlStepInfo = new Gson().fromJson(response.body().string(), UserPlStepInfo.class);
                        UserPlStepInfo.DataBean dataBean = userPlStepInfo.getData().get(0);
                        if (dataBean != null) {
                            dataBeanSparseArray.put(index, dataBean);
                        }
                    }
                    refresh();
                }
            });
        }

    }

    private void refresh() {
        responseCount++;
        if (responseCount >= 20) {
            runOnUiThread(() -> adapter.notifyDataSetChanged());
        }
    }

    static class ViewHolder {
        public View rootView;
        public TextView tv_rname;
        public TextView tv_item_four_gv_numleft;
        public TextView tv_item_four_gv_numright;
        public LinearLayout line_item_gv_four;

        public ViewHolder(View rootView) {
            this.rootView = rootView;
            this.tv_rname = (TextView) rootView.findViewById(R.id.tv_rname);
            this.tv_item_four_gv_numleft = (TextView) rootView.findViewById(R.id.tv_item_four_gv_numleft);
            this.tv_item_four_gv_numright = (TextView) rootView.findViewById(R.id.tv_item_four_gv_numright);
            this.line_item_gv_four = (LinearLayout) rootView.findViewById(R.id.line_item_gv_four);
        }

    }

}
